
//引入http模块
var http = require('http')
//fs模块
var fs = require('fs')
//url模块
var url = require('url')
//path模块
var path = require('path')
// 引入 events 模块
var events = require('events');

var EventEmitter = new events.EventEmitter()
//获取后缀名
var mimeModel = require('./model/getMime')
//获取后缀名2
var mimeModelFile = require('./model/getMimeFromFile')


http.createServer(function (req,res) {


    var pathName = req.url
    //获取真正的path路径，不带入参数传值
    pathName = url.parse(pathName).pathname
    if (pathName == '/') {
        console.log('开始默认加载')
        pathName = '/index.ejs' /*默认加载的首页*/
    }

    if (pathName != '/favicon.ico') {//过滤请求favicon.ico
        //文件操作获取static下面的index.html
        fs.readFile('./EJS/static/'+pathName, function (err,data) {
            if (err) {
                console.log(404)
                fs.readFile('../EJS/static/404.html',function (err,data404) {
                    console.log(data404)
                    res.writeHead(404,{"Content-Type":"text/html;charset='utf-8'"})
                    res.write(data404==null?'':data404)
                    res.end() /*结束响应*/
                })
            }else {/*返回这个文件*/
                //获取文件后缀名
                var extName = path.extname(pathName)
                var httpType = mimeModelFile.getMime(fs,extName,EventEmitter)
                
                EventEmitter.on('get_extName',function (httpType) {
                    res.writeHead(200,{"Content-Type":httpType+";charset='utf-8'"})
                    res.write(data)
                    // res.write('23123')
                    res.end() /*结束响应*/
                })
                
                res.writeHead(200,{"Content-Type":httpType+";charset='utf-8'"})
                res.write(data)
                // res.write('23123')
                res.end() /*结束响应*/
            }
        })
    }

}).listen(8008)